package com.hqyj.system.shiro;

import com.hqyj.system.model.Permission;
import com.hqyj.system.model.Role;
import com.hqyj.system.model.User;
import com.hqyj.system.service.PermissionService;
import com.hqyj.system.service.RoleService;
import com.hqyj.system.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;

/**
 * @ClassName CustomRealm
 * @Description
 * @Author zlf
 * @Date 2021/9/17 14:14
 * @Version 1.0
 **/

public class CustomRealm extends AuthorizingRealm {
    @Autowired
    public UserService userService;
    @Autowired
    public RoleService roleService;
    @Autowired
    public PermissionService permissionService;

    //1.认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1.认证
        // ---->第一步从token中取出身份信:token是用户输入的
        String username = (String) authenticationToken.getPrincipal();
//        System.out.println("-----------  //1.认证--------AuthenticationInfo----------" + username);
        // ---->第二步（查询数据库）:根据用户输入的userCode从查询数据
        User user_db = userService.queryUserByUsername(username);
//        System.out.println("-----------  //2.认证--------AuthenticationInfo----------" + user_db);
        // 如果查询不到返回null
        if (user_db == null) {
            return null;
        }
        // ---->第三步（查询数据库）:根据用户输入的userCode从查询数据
        //获取当前用户的会话域
        Session session = SecurityUtils.getSubject().getSession();
        //把登录用户信息保存到Session
        session.setAttribute("USER", user_db);
        //准备值
        String password = user_db.getPassword();
        //设置realm的名称
        String realmName = this.getName();
        //盐
        String salt = user_db.getSalt();

        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username,
                password, ByteSource.Util.bytes(salt), realmName);
        return simpleAuthenticationInfo;
    }

    //2.授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //1.拿到待授权用户账号
        String username = (String) principalCollection.getPrimaryPrincipal();
        System.out.println("-----------  //1.授权------AuthorizationInfo--------" + username);
        //2.查询数据库
        User user_db = userService.queryUserByUsername(username);
        //登录用户ID
        int userId = user_db.getUserId();

        //3.根据用户：查询--角色--集合
        HashSet<String> roles = new HashSet<>();
        List<Role> roleList = roleService.queryRoleByUserId(userId);
        for (Role role : roleList) {
            roles.add(role.getRoleCode());
        }


        //4.根据用户：查询--权限--集合集合
        HashSet<String> permissions = new HashSet<>();
        List<Permission> permissionList = permissionService.queryPermissionByUserId(userId);
        for (Permission permission : permissionList) {
            permissions.add(permission.getPermissionCode());
        }

        //创建权限授权对象，收集：1、角色--集合；2、权限--集合集合
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(roles);
        info.addStringPermissions(permissions);

        return info;
    }

}
